const state = {
    cartProduct: []
}

const mutations = {
    addToCart(state, product) {
        const result = state.cartProduct.find(item => item.id === product.id)

        if (result) {
            result.count++
                result.totalPrice = result.count * result.price
        } else {
            state.cartProduct.push({
                ...product,
                count: 1,
                totalPrice: product.price
            })
        }
    },

    deleteCount(state, prod) {
        const result = state.cartProduct.find(item => item.id === prod.id)

        if (result) {
            result.count--;
            if (result.count <= 0) {
                state.cartProduct.splice(state.cartProduct.findIndex(item => item.id === prod.id), 1)
            }
        } else {
            throw new Error('错误！！！')
        }
    },

    incrementCount(state, prod) {
        const result = state.cartProduct.find(item => item.id === prod.id)

        if (result) {
            result.count++
        }
    }
}

const actions = {

}

const getters = {
    totalPrice(state) {
        return state.cartProduct.reduce((sum, prod) => sum + prod.price * prod.count, 0)
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions,
    getters
}